import { Player } from './Player';
import { _decorator, Component, Collider2D, Contact2DType, IPhysics2DContact, RigidBody2D, Vec2, v2, isValid, math, find, UITransform,} from 'cc';
import { Brick } from './Brick';
import { GameSceneUI, GameState } from './GameSceneUI';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Component {

    //@property
    speed:number = 0;

    isShoot:boolean=false;

    collider:Collider2D = null;

    public velocity:Vec2=null;

    ballID:number = 0;

    cavasHeught:number = 0;

    start() {

        this.collider = this.getComponent(Collider2D);
        if (this.collider) {
            this.collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContac, this);
        }

        const canvas = find('Canvas');
        this.cavasHeught = -canvas.position.y;
    }

    protected onDestroy(){
        if (this.collider) {
            // 注销碰撞回调
            this.collider.off(Contact2DType.BEGIN_CONTACT, this.onBeginContac, this);
        }
    }

    protected onLoad(){
        
    }

    update(deltaTime: number) {
        
        if(this.isShoot ==false ) // || GameSceneUI.getInstance().getGameState() == GameState.Over
        {
            return;
        }

        if(this.velocity != null)
        {
            const position = this.node.position;
            this.node.setPosition(position.x+this.velocity.x*deltaTime*this.speed,position.y+this.velocity.y*deltaTime*this.speed,position.z);
            
            // 同步 velocity 到 RigidBody2D
            let rigidBody = this.getComponent(RigidBody2D);
            if (rigidBody) {
                rigidBody.linearVelocity = this.velocity;
            }
        }

        if(this.node.position.y < this.cavasHeught)
        {
            // 延迟一帧删除
            this.scheduleOnce(() => {
                if(isValid(this))
                {
                    GameSceneUI.getInstance().BallDestory(this.ballID);
                    this.node.destroy();
                }
            });
        }
    }


    onBeginContac(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
        const BrickNode = otherCollider.getComponent(Brick);
        if(BrickNode)
        {
            GameSceneUI.getInstance().FitBrick(BrickNode.getBrickID());
        }
        else
        {
            GameSceneUI.getInstance().playerContacAudio();
        }

        //此处用于解决当有一个底部墙体时，球体会从底部反弹上来碰撞到玩家的底部碰撞面，没有这行代码，也会进行反弹，不会穿过玩家 原理是修改球体的分组，使其不和玩家产生碰撞逻辑
        if(this.node.position.y < GameSceneUI.getInstance().getPlayerPosY())
        {
            selfCollider.group = 64;//64 为playerball  分组，是为此单独设定的一个分组，只解决这一情况
        }
        else
        {
            selfCollider.group = 2;//2 为ball分组，球体的原分组
        }

        let normal = contact.getWorldManifold().normal;
        let velocity = this.velocity;

        // 计算反弹速度
        let dot = Vec2.dot(velocity, normal);
        if (dot < 0) 
        {
            let bounceVelocity = velocity.subtract(normal.multiplyScalar(2 * dot));

            this.velocity = bounceVelocity.normalize().multiplyScalar(this.velocity.length());
            if(this.velocity.x < 0)
            {
                this.velocity.x = -0.75;
            }
            else
            {
                this.velocity.x = 0.75;
            }

            if(this.velocity.y < 0)
            {
                this.velocity.y = -0.75;
            }
            else
            {
                this.velocity.y = 0.75;
            }
        }
        else
        {
            console.warn("onBeginContac Error !!!")
        }
    }

    public changeShoot(isShoot:boolean)
    {
        this.isShoot = isShoot;
    }

    public getShoot():boolean
    {
        return this.isShoot;
    }

    public SetBallID(ID:number)
    {
        this.ballID = ID;
    }

    public GetBallID():number{
        return this.ballID;
    }

    public SetVelocity(velocity:Vec2)
    {
        this.velocity = velocity;
    }

    public changeSpeed(newSpeed:number)
    {
        this.speed = newSpeed;
    }

    public getSpeed():number
    {
        return this.speed;
    }

    public InitVelocity()
    {
        // 生成随机角度（-45° 到 45° 之间的向上角度）
        const minAngle = -45; // 左侧80度
        const maxAngle = 45;  // 右侧80度
        const randomAngle = math.randomRange(minAngle, maxAngle);
        
        // 转换为弧度
        const radians = randomAngle * Math.PI / 180;
        
        // 计算向量分量（Y轴始终为正）
        const newX = Math.sin(radians); // 使用sin获取水平分量
        const newY = Math.cos(radians); // 使用cos获取垂直分量（保证正数）
        this.velocity = v2(newX , newY );
    }

    //改变球的分组为玩家
    public changeBallGroupToPlayer()
    {
        const selfCollider = this.node.getComponent(Collider2D);
        selfCollider.group = 64;//64 为playerball  分组，是为此单独设定的一个分组，只解决这一情况
    }
}
